# -*- coding: utf-8 -*-

"""
上下文管理器
"""


def exe_try():
    try:
        print("code started")
        raise KeyError
        return 1
    except KeyError as e:
        print('key error')
        return 2
    else:
        print("else")
        return 3
    finally:
        print("finally")
        return 4


# 上下文管理器协议
class ContextManager:
    def __enter__(self):
        print("enter")
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        print("exit")
        return True

    def do_something(self):
        print("do something")

def context_test():
    with ContextManager() as cm:
        cm.do_something()

if __name__ == '__main__':
    # print(exe_try())
    context_test()
